// pages/count/count.js
let network = require("../../utils/network/network.js")
let api = require("../../utils/network/config.js").api;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imageURL: '/assets/scan/scan.png',
    totalPrice: 0,
    selectedDetectIndexList: [],
    selectedDetectList: [],
    detectList: []
  },
  onLoad(options) {
    let detectList = JSON.parse(options.detectList)
    this.setData({
      detectList: detectList
    })
  },
  onShow() {


    this.selectAllItem()
    this.calcTotalPrice()
  },
  onChange(event) {
    this.setData({
      selectedDetectIndexList: event.detail,
    });
    this.calcTotalPrice()
  },
  getSelectedDetect() {

  },
  calcTotalPrice() {
    let selectedIndexList = this.data.selectedDetectIndexList
    let detectList = this.data.detectList
    let selectedDetectList = []
    let totalPrice = 0
    selectedIndexList.forEach((ele, index) => {
      let idx = Number(ele)
      totalPrice = totalPrice + detectList[idx].detectNum * detectList[idx].stick.stickPrice
      selectedDetectList.push(detectList[idx])
    })
    this.setData({
      totalPrice: totalPrice,
      selectedDetectList: selectedDetectList
    })
  },
  toggle(event) {
    const {
      index
    } = event.currentTarget.dataset;

    const checkbox = this.selectComponent(`.checkboxes-${index}`);
    checkbox.toggle()
  },

  noop() {},

  selectAllItem() {
    let listLength = this.data.detectList.length
    let selectedIdx = []
    for (let i = 0; i < listLength; i++) {
      selectedIdx[i] = i.toString()
    }
    this.setData({
      selectedDetectIndexList: selectedIdx
    })
  },
  saveDetect() {
    let detectedSticks = []
    let selectedDetectList = this.data.selectedDetectList
    if (selectedDetectList.length == 0) {
      wx.showToast({
        title: '暂无可结算内容',
        icon: 'none'
      })
      return
    }
    selectedDetectList.forEach((ele, index) => {
      let detect = {
        detectNum: ele.detectNum,
        detectTime: ele.detectTime,
        resultUrl: ele.resultUrl,
        stickId: ele.stick.stickId,
        //userId: getApp().globalData.userInfo.uid
        userId: 22
      }
      detectedSticks[index] = detect
    })

    let orderDto = {
      detectedSticks: detectedSticks,
      totalPrice: this.data.totalPrice
    }
    network.fetch({
        url: api.order_save,
        inBody: true,
        data: orderDto,
        method: 'POST',
      })
      .then(res => {
        console.log(res)
        wx.navigateBack()
      })
  }
})